<template>
  <div>
    <!-- 面包屑导航 -->
    <el-header>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>订单管理</el-breadcrumb-item>
        <el-breadcrumb-item>订单列表</el-breadcrumb-item>
      </el-breadcrumb>
    </el-header>

    <!-- 主体部分 -->
    <el-card>
      <!-- 搜索框 -->
      <el-input class="search" placeholder="请输入内容" @clear="getTableData"
                v-model="search" clearable @keyup.enter.native="getTableData">
        <template slot="append">
          <!-- 搜索按钮 -->
          <el-button icon="el-icon-search" @click="getTableData"></el-button>
        </template>
      </el-input>

      <!-- 订单列表table -->
      <el-table :data="tableData" border stripe>
        <!-- 下拉展开行 用于展示订单所属商品信息 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-form class="showGood" label-position="left" inline>
              <el-form-item label="商品 ID">
                <span>{{ scope.row.good_id }}</span>
              </el-form-item>
              <el-form-item label="商品名称">
                <span>{{ scope.row.good__name }}</span>
              </el-form-item>
              <el-form-item label="所属分类">
                <span>{{ scope.row.good__category__name }}</span>
              </el-form-item>
              <el-form-item label="商品单价">
                <span>{{ scope.row.good__price }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column type="index" label="" width="50px"></el-table-column>
        <el-table-column prop="id" label="订单编号"></el-table-column>
        <el-table-column prop="num" label="购买数量" width="90px"></el-table-column>
        <el-table-column prop="total_pay" label="总价" width="120px"></el-table-column>
        <!-- 是否付款列 -->
        <el-table-column label="是否付款" width="80px">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.is_pay" type="success">已付款</el-tag>
            <el-tag v-else type="danger">未付款</el-tag>
          </template>
        </el-table-column>
        <!-- 是否发货列 -->
        <el-table-column label="是否发货" width="80px">
          <template slot-scope="scope">
            {{ scope.row.express_code.length ? '是' : '否' }}
          </template>
        </el-table-column>
        <el-table-column prop="express_code" label="物流单号" width="180px"></el-table-column>
        <el-table-column label="创建时间" width="200px">
          <template slot-scope="scope">
            {{ scope.row.date|standardTime }}
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column label="操作" width="150px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini"
                       @click="setOrderClick(scope.row)">修改
            </el-button>
            <!-- 查询物流按钮 -->
            <el-button type='success' icon="el-icon-location" size="mini"
                       @click="expressClick(scope.row.express_code)"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 底部分页区域 -->
      <el-pagination
              @size-change="sizeChange"
              @current-change="currentChange"
              :current-page="page"
              :page-sizes="[5, 8, 12, 16]"
              :page-size="num"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
      </el-pagination>
    </el-card>

    <!-- 修改订单弹出框 -->
    <el-dialog title="修改订单" width="30%"
               :visible.sync="setOrderForm.visible">
      <!-- 修改订单的表单 -->
      <el-form :model="setOrderForm.data" ref="setOrderForm"
               label-width="100px" :rules="setOrderForm.rules">
        <el-form-item label="选择地址：" prop="city">
          <!-- 城市选择器 -->
          <el-cascader expand-trigger="hover" clearable
                       :options="setOrderForm.cityData"
                       :props="setOrderForm.cityProps"
                       v-model="setOrderForm.data.city">
          </el-cascader>
        </el-form-item>
        <!-- 详细地址输入框 -->
        <el-form-item label="详细地址：" prop="detailAddress">
          <el-input v-model="setOrderForm.data.detailAddress"
                    placeholder="请输入详细地址"></el-input>
        </el-form-item>
        <!-- 物流单号输入框 -->
        <el-form-item label="物流单号：" prop="express_code">
          <el-input v-model="setOrderForm.data.express_code"
                    disabled v-if="setOrderForm.expressDisabled"
                    placeholder="未付款不能填写物流单号"></el-input>
          <el-input v-model="setOrderForm.data.express_code" v-else></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <!-- 取消按钮 -->
        <el-button @click="setOrderForm.visible = false">取 消</el-button>
        <!-- 确定按钮 -->
        <el-button type="primary" @click="setOrderSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 时间线弹出框 -->
    <el-dialog title="物流信息" width="50%"
               :visible.sync="timeLine.visible">
      <el-timeline :reverse="false">
        <el-timeline-item v-for="(item,index) in timeLine.data"
                          :key="index" :timestamp="item.time"
                          :icon="item.icon" :color="item.color"
                          :type="item.type?'success':'info'">
          {{ item.context }}
        </el-timeline-item>
      </el-timeline>
    </el-dialog>
  </div>
</template>

<script>
import cityData from '@/assets/js/CityData'

export default {
  name: 'Orders',
  data() {
    return {
      // 订单列表数据
      tableData: [],
      // 当前页码
      page: 1,
      // 一页条数
      num: 8,
      // 数据总条数
      total: 0,
      // 搜索框输入内容
      search: '',
      // 修改订单的表单
      setOrderForm: {
        data: {
          // 要修改的订单的id
          id: 0,
          // 所在城市
          city: [],
          // 详细地址
          detailAddress: '',
          // 物流单号 可不填
          // 若填写发货状态会改为true
          express_code: ''
        },
        // 快递单号是否可填（未付款不允许填写快递单号）
        expressDisabled: false,
        // 修改订单弹出框是否显示
        visible: false,
        // 城市级联选择器配置
        cityProps: {
          label: 'label',
          children: 'children',
          value: 'value'
        },
        rules: {
          city: [{ required: true, message: '必须选择城市', trigger: 'blur' }],
          detailAddress: [{ required: true, message: '必须输入详细地址', trigger: 'blur' }],
          express_code: [{ max: 20, message: '物流单号最长不能超过20字符', trigger: 'blur' }]
        },
        // 所有城市可选项信息
        cityData
      },
      // 物流信息时间线数据
      timeLine: {
        data: {},
        visible: false
      }
    }
  },
  filters: {
    // 时间格式化
    standardTime(time) {
      let res = new Date(time)
      // 不足补0
      let y = res.getFullYear().toString().padStart(4, '0')
      // 月份坑爹，1月为0
      let m = (res.getMonth() + 1).toString().padStart(2, '0')
      let d = res.getDate().toString().padStart(2, '0')
      let hh = res.getHours().toString().padStart(2, '0')
      let mm = res.getMinutes().toString().padStart(2, '0')
      let ss = res.getSeconds().toString().padStart(2, '0')
      return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
    }
  },
  methods: {
    // 获取订单列表数据
    async getTableData() {
      let { data: res } = await this.$ajax.get('orders/', {
        params: { page: this.page, num: this.num, search: this.search }
      })
      if (res.status === 'success') {
        this.tableData = res.data
        this.total = res.total
        this.$message.success('获取订单列表成功')
      } else
        this.$message.error('获取订单列表失败')
    },
    // 页面尺寸改变
    sizeChange(num) {
      this.num = num
      this.getTableData()
    },
    // 页码改变
    currentChange(page) {
      this.page = page
      this.getTableData()
    },
    // 修改按钮点击
    setOrderClick(row) {
      this.setOrderForm.visible = true
      let data = this.setOrderForm.data
      this.$nextTick(() => {
        // 设置表单默认选项
        data.id = row.id
        if (!row.address.length) {
          data.city = ''
          data.detailAddress = ''
        } else {
          let address = row.address.split('#')
          data.city = address[0].split('/')
          data.detailAddress = address[1]
        }
        this.setOrderForm.expressDisabled = !row.is_pay
        data.express_code = row.express_code
      })
    },
    // 修改订单 表单提交
    setOrderSubmit() {
      this.$refs.setOrderForm.validate(async valid => {
        if (!valid) return
        // 发送请求
        let data = this.setOrderForm.data
        let address = data.city.join('/') + '#' + data.detailAddress
        let { data: res } = await this.$ajax.post('orders/set/',
                this.$ajax.stringify({
                  id: data.id,
                  address,
                  express_code: data.express_code
                }))
        if (res.status === 'OK') {
          this.$message.success('修改订单信息成功')
          this.setOrderForm.visible = false
          await this.getTableData()
        } else
          this.$message.error('修改订单信息失败')
      })
    },
    // 查询物流点击事件
    async expressClick(express_code) {
      if (!express_code.length)
        return this.$message.error('没有物流单号，无法查询')
      let { data: res } = await this.$ajax.get(`express/${express_code}/`)
      if (res.status === 'success') {
        res.data[0].type = res.type
        this.timeLine.data = res.data
        console.log(this.timeLine.data)
        this.timeLine.visible = true
        this.$message.success('获取物流成功')
      } else
        this.$message.error('获取物流失败')
    }
  },
  created() {
    this.getTableData()
  }
}
</script>

<style scoped>
.el-header {
  display: flex;
  align-items: center;
}

.search {
  width: 300px;
  margin-right: 15px;
}

.el-table {
  margin-top: 15px;
}

.el-pagination {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.showGood .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.showGood /deep/ label {
  width: 90px;
  color: #99a9bf;
}

.el-timeline {
  padding-right: 40px;
}
</style>